package com.example.ReactorModel;

import com.example.util.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class EchoHandler implements Runnable{

    final SocketChannel channel;
    final SelectionKey sk;
    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    static final int RECIEVING = 0,SENDING = 1;
    int state = RECIEVING;

    public EchoHandler(Selector selector,SocketChannel c) throws IOException {
        channel = c;
        c.configureBlocking(false);
        sk = channel.register(selector,0);
        sk.attach(this);
        sk.interestOps(SelectionKey.OP_READ);
        selector.wakeup();
    }

    @Override
    public void run() {
        try{
            if(state == SENDING){
                //写入通道
                channel.write(byteBuffer);
                //写完后，准备从通道读，byteBuffer切换成写模式
                byteBuffer.clear();
                //写完后，注册read就绪事件
                sk.interestOps(SelectionKey.OP_READ);
                //写完后，进入接收到状态
                state = RECIEVING;
            }else if(state == RECIEVING){
                //从通道读
                int length = 0;
                while ((length = channel.read(byteBuffer))>0){
                    Logger.info(new String(byteBuffer.array(),0,length));
                }
                //读完后，准备写入通道，byteBuffer切换成读模式
                byteBuffer.flip();
                //读完后，注册write就绪事件
                sk.interestOps(SelectionKey.OP_WRITE);
                //读完后，进入发送状态
                state = SENDING;
            }

        }catch (IOException ex){
           ex.printStackTrace();
           sk.cancel();
           try {
               channel.finishConnect();
           }catch (IOException e){
               e.printStackTrace();
           }
        }
    }
}
